﻿
using Microsoft.EntityFrameworkCore;
using FreeRedis;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Mvc;
using static System.Reflection.Metadata.BlobBuilder;
using Newtonsoft.Json.Linq;
using CQIE.LabAssist.Models;
using System;
using CQIE.LabAssist.PublicHelp;
using System.Drawing;
using System.Reflection.Emit;
using Microsoft.Extensions.Caching.Distributed;
namespace CQIE.LabAssist.DataAccesss
{

    public class LaboratoryService : ILaboratoryService
    {
        private readonly _DbContext _Db;
        private readonly JwtHelp _jwtHelper;

        private IDistributedCache RedisCache;

        public LaboratoryService(JwtHelp jwtHelper, _DbContext db, IDistributedCache redisCache)
        {
            _jwtHelper = jwtHelper;
            _Db = db;
            RedisCache = redisCache;
        }

        /// <summary>
        /// 根据用户id获取实验室
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public JsonResult getLaboratoryByUserId(int userId)
        {
            var res=_Db.Laboratories.Include(w=>w.floor).ThenInclude(w=>w.building).Where(w=>w.UserId==userId).ToList().Select(w => new
            {
                id=w.Id,
                name=w.Name,
                number=w.Nubmer,
                buildname=w.floor.building.Name,
                floorname=w.floor.Name,
                
            });

            return new JsonResult(res);
        }

        /// <summary>
        /// 根据楼层id获取所有教室
        /// </summary>
        /// <param name="floorid"></param>
        /// <returns></returns>
        public JsonResult getAllLaboratory(int floorid)
        {
            //获取redis缓存数据
            string ? RedisResult = RedisCache.GetString("AllLab"+ floorid.ToString());

            if (RedisResult == null)
            {
                var res = _Db.Laboratories.Where(w => w.floorId == floorid).Include(w => w.floor).Include(u => u.Admin).ToList();

                // 创建一个 JsonSerializerSettings 对象
                var settings = new JsonSerializerSettings
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                };

                // 将结果转换为JSON字符串
                string jsonString = JsonConvert.SerializeObject(res, settings);

                // 设置缓存的过期时间为 10s
                var options = new DistributedCacheEntryOptions
                {
                    //30s
                    AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(10),
                };
                RedisCache.SetString("AllLab" + floorid.ToString(), jsonString, options);

                return new JsonResult(res);
            }
            else
            {
                var cachedData = RedisCache.GetString("AllLab" + floorid.ToString());
                var AllLaboratories = JsonConvert.DeserializeObject<List<Laboratory>>(cachedData);
                // 返回JsonResult
                return new JsonResult(AllLaboratories);
            }
        }

        /// <summary>
        /// 新增实验室
        /// </summary>
        /// <param name="laboratory"></param>
        /// <returns></returns>
        public bool addLaboratory(Laboratory laboratory)
        {
            var r= _Db.Laboratories.Where(w => w.Nubmer == laboratory.Nubmer).FirstOrDefault();
            if (r!=null)
            {
                return false;
            }
            Laboratory f = new Laboratory();
            f.Name = laboratory.Name;
            f.Nubmer = laboratory.Nubmer;
            f.floorId = laboratory.floorId;
            f.UserId = laboratory.UserId;
            f.Admin=_Db.Users.Where(w => w.Id == laboratory.UserId).FirstOrDefault();
            f.floor= _Db.Floors.Where(w => w.Id == laboratory.floorId).FirstOrDefault();
            _Db.Laboratories.Add(f);
            return _Db.SaveChanges() > 0;
        }

        /// <summary>
        /// 删除实验室
        /// </summary>
        /// <param name="laboratory"></param>
        /// <returns></returns>
        public bool deleteLaboratory(int labId)
        {
            Laboratory Floors = _Db.Laboratories.Where(w => w.Id == labId).FirstOrDefault();
            _Db.Laboratories.Remove(Floors);
            return _Db.SaveChanges() > 0;
          
        }

        /// <summary>
        /// 修改实验室信息
        /// </summary>
        /// <param name="lab"></param>
        /// <returns></returns>
        public bool updateLaboratory(Laboratory lab)
        {
            Laboratory f = _Db.Laboratories.Where(w => w.Id == lab.Id).FirstOrDefault();
            f.Name = lab.Name;
           
            f.Nubmer = lab.Nubmer;
            f.floorId = lab.floorId;
            f.UserId = lab.UserId;
            f.Admin = _Db.Users.Where(w => w.Id == lab.UserId).FirstOrDefault();
            f.floor = _Db.Floors.Where(w => w.Id == lab.floorId).FirstOrDefault();

            _Db.Laboratories.Update(f);
            return _Db.SaveChanges() > 0;
        }
    }


}
